import Vue from 'vue'
import router from './router'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({
	showSpinner: false
}) // NProgress Configuration

const whiteList = ['/login'] // 白名单

router.beforeEach(async(to, from, next) => {
	// start progress bar
	NProgress.start()

	// set page title
	document.title = getPageTitle(to.meta.title)

	// determine whether the user has logged in
	const hasRole = sessionStorage.getItem('PERTYPE')
	if (hasRole == 0) {
		if (to.path === '/login') {
			// if is logged in, redirect to the home page
			if (to.query.Code && to.query.url) {
				next()
			} else {
				next({
					path: '/'
				})
			}
			NProgress.done()
		} else {
			next()
		}
	} else {
		/* has no token*/
		if (whiteList.indexOf(to.path) !== -1) {
			// 在免登录白名单，直接进入
			next()
		} else {
			// 没有权限的,全部重定向到登录页
			next(`/login?redirect=${to.path}`)
			NProgress.done()
		}
	}
})

router.afterEach(() => {
	// finish progress bar
	NProgress.done()
})
